package com.cloudfast.oauth.config;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;

import com.cloudfast.context.CloudSecurity;
import com.cloudfast.oauth.client.CustomAuthenticationEntryPoint;

/**
 * 资源配置类
 *
 * @author liuyw
 * @date 2022年8月29日
 */
@Configuration
@EnableResourceServer
public class ResourceServerConfigurer extends ResourceServerConfigurerAdapter {

    @Autowired
    private CloudSecurity cloudSecurity;

    @Override
    public void configure(HttpSecurity httpSecurity) throws Exception {
        List<String> whiteList = cloudSecurity.getWhiteList();
        if (whiteList == null) {
            whiteList = new ArrayList<>();
        }
        String[] whiteListMethod = new String[whiteList.size()];
        for (int i = 0; i < whiteList.size(); i++) {
            whiteListMethod[i] = whiteList.get(i);
        }
        // 开启授权认证
        httpSecurity.csrf().disable().authorizeRequests().antMatchers(whiteListMethod).permitAll().anyRequest()
                .authenticated();
        // 开启跨域共享，跨域伪造请求限制=无效
        httpSecurity.cors().and().csrf().disable();
        // 使用当前会话
        httpSecurity.sessionManagement().sessionFixation().none();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources
                // 无效token异常类重写
                .authenticationEntryPoint(new CustomAuthenticationEntryPoint());
    }
}